//
//  OfficeBoardViewController.m
//  EducationAdminClient
//
//  Created by xuyingwei on 16/9/7.
//  Copyright © 2016年 周佳兴. All rights reserved.
//  学员端首页

#import "OfficeBoardViewController.h"
#import "FounctionCollectionCell.h"
#import "BusinessMenuViewController.h"
#import "MyButtonMainPage.h"
#import "SetUPViewController.h"
#import "ZCZBarViewController.h"
#import "ZJLoopScrollView.h"
#import "PersonalMissionViewController.h"
#import "MessageAlertViewController.h"
#import "TabBarOccupyingController1.h"
#import "ListsViewController.h"
#import "MJRefresh.h"
#import "JPUSHService.h"
#import "ThingsCollectionViewCell.h"
@interface OfficeBoardViewController (){
    
    ZJLoopScrollView *loopView;
    
    UITableView *leftTableView;//左菜单
    UITableView *rightTableView;//右菜单
    
}

@property(nonatomic,retain)NSDictionary *dic2;
@property(nonatomic,retain)NSMutableArray *menuArr;
@property(nonatomic,retain)NSMutableArray *secondArr;
@property(nonatomic,assign)BOOL isheng;
@property(nonatomic,retain)NSMutableArray *rightItemsArr;

@end

@implementation OfficeBoardViewController
static const CGFloat MJDuration = 0.5;
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    NSNotificationCenter *noti = [NSNotificationCenter defaultCenter];
    [noti postNotificationName:@"pan" object:@"canUse"];
    if(loopView)[loopView setContentOfSet];
    self.cusTabView.hidden = NO;
    loopView.autoScroll = YES;
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSInteger badge = [[ud objectForKey:@"badge"] integerValue];
    if (!_badgeLabel) {
        return ;
    }else{
        if (badge>0) {
            _badgeLabel.text = [NSString stringWithFormat:@"%zd",badge];
            _badgeLabel.hidden = NO;
            _borderView.hidden = NO;
        }else{
            _badgeLabel.hidden = YES;
            _borderView.hidden = YES;
        }
        
    }
    
}
-(UIView *)red{
    if (!_red) {
        _red = [[UIView alloc] init];
        _red.backgroundColor = [UIColor redColor];
        _red.layer.cornerRadius = 2.6f;
        
    }
    return _red;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear: animated];
    NSNotificationCenter *noti = [NSNotificationCenter defaultCenter];
    [noti postNotificationName:@"pan" object:@"remove"];
    loopView.autoScroll = NO;
    if (_red) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        NSString *badge = [ud objectForKey:@"badge"];
        if (badge.integerValue>0) {
            _red.hidden = NO;
        }else{
            _red.hidden = YES;
        }
    }
}

//NSLog(@"主项目程序");

-(void)viewDidLoad{
    [super viewDidLoad];
    
    //    self.cusTabView.hidden = YES;
    //*** top loop
    [self createLoop];
    _isheng=YES;
    _dic2= [[NSDictionary alloc]init];
    _menuArr = [[NSMutableArray alloc]init];
    _secondArr = [[NSMutableArray alloc]init];
    //    self.view.backgroundColor = [UIColor whiteColor];
    //    [self creatRightNav];
    //    [self creatLeftNav];
    self.dataArr = [[NSMutableArray alloc]init];
    
    
#pragma mark - jpush begain
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJPFNetworkDidSetupNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidClose:)
                          name:kJPFNetworkDidCloseNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidRegister:)
                          name:kJPFNetworkDidRegisterNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJPFNetworkDidLoginNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidReceiveMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(serviceError:)
                          name:kJPFServiceErrorNotification
                        object:nil];
    
#pragma mark - jpush end
    
    
    
    
    //NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    
    UIButton *leftNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftNavBtn.frame = CGRectMake(0, 0, 37/2, 37/2);
    //形状-16@2x
    [leftNavBtn setBackgroundImage:[UIImage imageNamed:@"形状-4"] forState:UIControlStateNormal];
    [leftNavBtn addTarget:self action:@selector(LeftClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:leftNavBtn];
    self.navigationItem.leftBarButtonItem = item;
    
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightBtn.frame = CGRectMake(0, 0, 37/2, 37/2);
    //
    [self.rightBtn setBackgroundImage:[UIImage imageNamed:@"形状-16"] forState:UIControlStateNormal];
    [self.rightBtn addTarget:self action:@selector(RightClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *ritem = [[UIBarButtonItem alloc]initWithCustomView:self.rightBtn];
    self.navigationItem.rightBarButtonItem = ritem;
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *badge = [ud objectForKey:@"badge"];
    NSLog(@"%zd",badge.integerValue);
    
    if (badge.integerValue>0) {
        NSLog(@"有未读消息");
        [self.rightBtn addSubview:self.red];
        [self.red mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.rightBtn.mas_top);
            make.right.equalTo(self.rightBtn.mas_right).offset(2.5);
            make.width.equalTo(@(5));
            make.height.equalTo(@(5));
        }];
    }else{
        NSLog(@"无未读消息");
        
    }

    
    [self getDocumentData];
    [self setTitleLabelText:@"学员端"];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    [flowLayout setMinimumLineSpacing:0];
    [flowLayout setItemSize:CGSizeMake([UIScreen mainScreen].bounds.size.width/2, 230/2)];//设置cell的尺寸
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];//设置其布局方向
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);//设置其边界
    flowLayout.minimumInteritemSpacing = 0;
    //其布局很有意思，当你的cell设置大小后，一行多少个cell，由cell的宽度决定
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) collectionViewLayout:flowLayout];
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(loopView.mas_bottom);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom).offset(-50);
    }];
    
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerClass:[ThingsCollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];//注册必不可少
    
    //    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    //        [self loadNewData];
    //    }];
}
- (void)RightClick:(UIButton *)sender{
    MessageAlertViewController *mavc = [[MessageAlertViewController alloc] init];
    mavc.tabbarView = self.cusTabView;
    [self.navigationController pushViewController:mavc animated:YES];
}
- (void)LeftClick:(UIButton *)sender{
    ZCZBarViewController *zvc = [[ZCZBarViewController alloc] initWithBlock:^(NSString * data, BOOL succeed) {
        if(succeed){
            NSString *urlStr = [[NSString alloc]initWithString:data];
            NSLog(@"%@", urlStr);
            
            //                NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
            //                [param setObject:str forKey:@"stuId"];
            
            [NetRequest requestUrl:urlStr andParamas:nil andReturnBlock:^(NSData *data, NSError *error) {
                if(!error&&data!=nil){
                    NSString *str = [[NSString alloc]initWithData:data  encoding:NSUTF8StringEncoding];
                    NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                    NSLog(@"%@", obj);
                    if ([str isEqualToString:@"1"]) {
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"考勤" message:@"考勤成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        alert.delegate = self;
                        [alert show];
                    }else{
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"考勤" message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        alert.delegate = self;
                        [alert show];
                    }
                    NSLog(@"sucess!");
                    //                    _sucess = YES;
                }else{
                    
                    NSString *str = [NSString stringWithFormat:@"系统错误！%@",urlStr];
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"考勤" message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    alert.delegate = self;
                    [alert show];
                    NSLog(@"%@",error);
                    //                    _sucess = NO;
                }
                
            }];
            //            NSLog(@"%@",erro);
            
        }
        
    }];
    
    [self.navigationController presentViewController:zvc animated:YES completion:^{
        
    }];;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView==leftTableView) {
        static NSString *str = @"identifier";
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:str];
        if(cell==nil){
            cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
        NSDictionary *dic = [_menuArr objectAtIndex:indexPath.row];
        if(dic.allKeys.count>1){
            
            NSMutableString *strMenuName = [NSMutableString stringWithFormat:@"%@", [dic objectForKey:@"menuName"]];
            if ([strMenuName rangeOfString:@"手机端"].location != NSNotFound) {
                [strMenuName replaceCharactersInRange:[strMenuName rangeOfString:@"手机端"] withString:@""];
            }
            
            cell.textLabel.text = strMenuName;
            float deviceNumber= [[[UIDevice currentDevice] systemVersion] floatValue];
            if(deviceNumber>9.9){
                cell.textLabel.font =[UIFont systemFontOfSize:14];
            }
            
            //int x = arc4random() % 7;
            
            //        cell.titleImg.image = [UIImage imageNamed:[NSString stringWithFormat:@"移动客户化_00%i", x+1]];
            //
            //        //         = [UIImage imageNamed:@"形状-9"];
            //        [cell changeRect:NO];
            
        }else{
            //        [cell changeRect:YES];
            //        cell.titleImg2.image =[UIImage imageNamed:[dic objectForKey:@"img"]];
        }
        //    cell.textLabel.text = @"123";
        return cell;
    }else{
        static NSString *str = @"identifier";
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:str];
        if(cell==nil){
            cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
        NSDictionary *dic = [_rightItemsArr objectAtIndex:indexPath.row];
        NSMutableString *strMenuName = [NSMutableString stringWithFormat:@"%@", [dic objectForKey:@"menuName"]];
        if ([strMenuName rangeOfString:@"手机端"].location != NSNotFound) {
            [strMenuName replaceCharactersInRange:[strMenuName rangeOfString:@"手机端"] withString:@""];
        }
        cell.textLabel.text = strMenuName;
        return cell;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(tableView==leftTableView){
        NSDictionary *dic = [_menuArr objectAtIndex:indexPath.row];
        NSMutableArray *nextArr = [[NSMutableArray alloc]init];
        for (NSDictionary *dica in _secondArr) {
            if ([[NSString stringWithFormat:@"%@", [dica valueForKey:@"parent_menuId"]] isEqualToString:[NSString stringWithFormat:@"%@", [dic valueForKey:@"menuId"]]]) {
                [nextArr addObject:dica];
            }
        }
        _rightItemsArr =[NSMutableArray arrayWithArray:nextArr];
        [rightTableView reloadData];
        
    }else{
        NSDictionary *dic = [_rightItemsArr objectAtIndex:indexPath.row];
        
        NSMutableArray *nextArr = [[NSMutableArray alloc]init];
        for (NSDictionary *dica in _secondArr) {
            if ([[NSString stringWithFormat:@"%@", [dica valueForKey:@"parent_menuId"]] isEqualToString:[NSString stringWithFormat:@"%@", [dic valueForKey:@"menuId"]]]) {
                [nextArr addObject:dica];
            }
        }
        if(nextArr.count<=0){
            NSString *classListStr = [NSString stringWithFormat:@"%@", [dic valueForKey:@"menuPageUrl"]];
            if ([classListStr rangeOfString:@"tableId="].location!=NSNotFound) {//课程表页面需要特殊跳转
                TabBarOccupyingController1 *tbOC = [[TabBarOccupyingController1 alloc]init];
                
                self.cusTabView.hidden = YES;
                
                tbOC.dataDic = dic;
                tbOC.fromPop = YES;
                [self.navigationController pushViewController:tbOC animated:YES];
                return;
            }
            
            ListsViewController *lv =[[ListsViewController alloc]init];
            lv.pageId = [dic valueForKey:@"pageId"];
            lv.tableId = [dic valueForKey:@"tableId"];
            
            [self.navigationController pushViewController:lv animated:YES];
        }else{
            
            
            
            BusinessMenuViewController *nv =[[BusinessMenuViewController alloc]init];
            nv.titleString = [dic objectForKey:@"menuName"];
            [self.navigationController pushViewController:nv animated:YES];
            nv.secondArr = [NSMutableArray arrayWithArray:nextArr];
            nv.allArr = [NSMutableArray arrayWithArray:_secondArr];
            
            //        nv.menu_url = [_dic2 objectForKey:@"timeInterface"];
            nv.cusTabView = self.cusTabView;
            
        }
        
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView==leftTableView){
        return [_menuArr count];
    }else{
        return [_rightItemsArr count];
    }
}

#pragma mark - JpushMethod begain
- (void)networkDidSetup:(NSNotification *)notification {
    //    _netWorkStateLabel.text = @"已连接";
    NSLog(@"已连接");
    //    _netWorkStateLabel.textColor = [UIColor colorWithRed:0.0 / 255
    //                                                   green:122.0 / 255
    //                                                    blue:255.0 / 255
    //                                                   alpha:1];
}

- (void)networkDidClose:(NSNotification *)notification {
    //    _netWorkStateLabel.text = @"未连接。。。";
    NSLog(@"未连接");
    //    _netWorkStateLabel.textColor = [UIColor redColor];
}

- (void)networkDidRegister:(NSNotification *)notification {
    NSLog(@"%@", [notification userInfo]);
    //    _netWorkStateLabel.text = @"已注册";
    //    _netWorkStateLabel.textColor = [UIColor colorWithRed:0.0 / 255
    //                                                   green:122.0 / 255
    //                                                    blue:255.0 / 255
    //                                                   alpha:1];
    //    _registrationValueLabel.text =
    //    [[notification userInfo] valueForKey:@"RegistrationID"];
    //    _registrationValueLabel.textColor = [UIColor colorWithRed:0.0 / 255
    //                                                        green:122.0 / 255
    //                                                         blue:255.0 / 255
    //                                                        alpha:1];
    NSLog(@"已注册");
}
- (void)networkDidLogin:(NSNotification *)notification {
    //    _netWorkStateLabel.text = @"已登录";
    ////    _netWorkStateLabel.textColor = [UIColor colorWithRed:0.0 / 255
    //                                                   green:122.0 / 255
    //                                                    blue:255.0 / 255
    //                                                   alpha:1];
    NSLog(@"已登录");
    
    if ([JPUSHService registrationID]) {
        //        _registrationValueLabel.text = [JPUSHService registrationID];
        NSLog(@"get RegistrationID");
    }
}
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *title = [userInfo valueForKey:@"title"];
    NSString *content = [userInfo valueForKey:@"content"];
    NSDictionary *extra = [userInfo valueForKey:@"extras"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    
    NSString *currentContent = [NSString
                                stringWithFormat:
                                @"收到自定义消息:%@\ntitle:%@\ncontent:%@\nextra:%@\n",
                                [NSDateFormatter localizedStringFromDate:[NSDate date]
                                                               dateStyle:NSDateFormatterNoStyle
                                                               timeStyle:NSDateFormatterMediumStyle],
                                title, content, [self logDic:extra]];
    NSLog(@"%@", currentContent);
    //
    //    [_messageContents insertObject:currentContent atIndex:0];
    //
    //    NSString *allContent = [NSString
    //                            stringWithFormat:@"%@收到消息:\n%@\nextra:%@",
    //                            [NSDateFormatter
    //                             localizedStringFromDate:[NSDate date]
    //                             dateStyle:NSDateFormatterNoStyle
    //                             timeStyle:NSDateFormatterMediumStyle],
    //                            [_messageContents componentsJoinedByString:nil],
    //                            [self logDic:extra]];
    //
    //    _messageContentView.text = allContent;
    //    _messageCount++;
    //    [self reloadMessageCountLabel];
}
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}
- (void)serviceError:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *error = [userInfo valueForKey:@"error"];
    NSLog(@"%@", error);
}

#pragma mark - JpushMethod end
#pragma mark - Refresh
-(void)loadNewData{
    
    
    [self.tbView.header beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //*** setting edit style
        
        
        
        // 刷新表格
        //        begin = 0;
        //        [self dataRequestWithBegining:begin andLimit:limit andIsFooter:NO];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tbView.header endRefreshing];
    });
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"aaaaa");
}
-(void)createLoop{
    
    
    
    loopView = [[ZJLoopScrollView alloc] init];
    loopView.autoScroll = YES;
    loopView.imageArray = @[@"移动客户化_09",@"移动客户化_09",@"移动客户化_09"];
    [self.view addSubview:loopView];
    loopView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 260/2);
    //    [loopView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.left.equalTo(_myTableHeader.mas_left);
    //        make.right.equalTo(_myTableHeader.mas_right);
    //        make.top.equalTo(_myTableHeader.mas_top);
    //        make.height.equalTo(FIVE);
    //
    //
    //    }];
    
}
-(void)getDocumentData{
    //    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *filename=getSaveFile(userName(),LOGINFOUNCTION);   //获取路径
    NSString *path=[filename stringByAppendingPathComponent:LOGINOK];
    
    NSData *dataNow = [NSData dataWithContentsOfFile:path];
    NSDictionary * dic;
    if(dataNow){
        
        dic = [NSJSONSerialization JSONObjectWithData:dataNow options:NSJSONReadingMutableContainers error:nil];  //读取数据
    }
    NSLog(@"%@",dic);
    _dic2 = dic;
    
    
    [self menuDataUse];
    
    NSLog(@"dic2 is:%@",_dic2);
}


-(void)creatRightNav{
    UIButton *rightNavBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 25, 25)];
    [rightNavBtn addTarget:self action:@selector(rightNavClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightNavBtn];
    [rightNavBtn setBackgroundImage:[UIImage imageNamed:@"移动客户化_05"] forState:UIControlStateNormal];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:rightNavBtn];
    self.navigationItem.rightBarButtonItem = item;
}

-(void)creatLeftNav{
    UIButton *rightNavBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 25, 25)];
    [rightNavBtn addTarget:self action:@selector(rightNavClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightNavBtn];
    [rightNavBtn setBackgroundImage:[UIImage imageNamed:@"移动客户化_03"] forState:UIControlStateNormal];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:rightNavBtn];
    self.navigationItem.leftBarButtonItem = item;
}

-(void)rightNavClick:(UIButton *)btn{
    //    self.navigationController.view.frame = CGRectMake(self.navigationController.view.frame.origin.x+300, self.navigationController.view.frame.origin.y, self.navigationController.view.frame.size.width, self.navigationController.view.frame.size.height);
    
    
    NSNotificationCenter *noti = [NSNotificationCenter defaultCenter];
    [noti postNotificationName:@"showLeftView" object:@"show"];
}


-(void)menuDataUse{
    
    NSMutableArray *arr  =[_dic2 objectForKey:@"roleFollowList"];
    [self.dataArr removeAllObjects];
    [self.collectionView.header endRefreshing];
    for (NSDictionary *dic in arr) {
        ThingsModel *model = [[ThingsModel alloc]init];
        model = [model initWithDictionary:dic error:nil];
        [self.dataArr addObject:model];
    }
    NSLog(@"%@",self.dataArr);
    [self.collectionView reloadData];
}

#pragma mark - collectionView dataSource Or delegate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    NSLog(@"%@",self.dataArr);
    return self.dataArr.count;
    
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//-(CGFloat )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
//
//}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"UICollectionViewCell";
    ThingsCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    cell.titleLa.text = @"";
    cell.titleImg.image = [UIImage imageNamed:[NSString stringWithFormat:@""]];
    
    ThingsModel *model = [self.dataArr objectAtIndex:indexPath.row];
    if(model.cnName){
        
        NSMutableString *strMenuName = [NSMutableString stringWithFormat:@"%@", model.cnName];
        if ([strMenuName rangeOfString:@"手机端"].location != NSNotFound) {
            [strMenuName replaceCharactersInRange:[strMenuName rangeOfString:@"手机端"] withString:@""];
        }
        
        cell.titleLa.text = strMenuName;
        
        int x = arc4random() % 7;
        
        cell.titleImg.image = [UIImage imageNamed:[NSString stringWithFormat:@"移动客户化_00%i", x+1]];
        
        //         = [UIImage imageNamed:@"形状-9"];
        [cell changeRect:NO];
        
    }else{
        [cell changeRect:YES];
        //        cell.titleImg2.image =[UIImage imageNamed:[dic objectForKey:@"img"]];
    }
    //    if (indexPath.row == _menuArr.count-2) {
    //        NSLog(@"q34");
    //        NSLog(@"%@", dic);
    //    }
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ThingsModel *model = [self.dataArr objectAtIndex:indexPath.row];
    if (!model.phonePageId||!model.tableId) {
        return;
    }
    //*** pop Which View
    
    
    ListsViewController *lv =[[ListsViewController alloc]init];
    lv.fromThings = YES;
    lv.pageId = [NSString stringWithFormat:@"%@", model.phonePageId];
    lv.tableId = [NSString stringWithFormat:@"%@", model.tableId];
    lv.model = model;
    [self.navigationController pushViewController:lv animated:YES];
    lv.cusTabView = self.cusTabView;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    UIView *view = [self createCollectionViewHeaderView];
    view.frame = CGRectMake(0, 0, collectionView.frame.size.width, 2+(320+56)/2);
    //    if(_isheng){
    [collectionView addSubview:view];
    //    }
    return CGSizeMake(collectionView.frame.size.width, 2+(320+56)/2);
}

//这个也是最重要的方法 获取Header的 方法。
//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//
//    return [self createCollectionViewHeaderView];
////    NSString *CellIdentifier = @"header";
//    //从缓存中获取 Headercell
////    HeaderCRView *cell = (HeaderCRView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CellIdentifier forIndexPath:indexPath];
//    return nil;
//}
-(UIView *)createCollectionViewHeaderView{
    
    UIView *thisTheSuperView = [[UIView alloc]init];
    
    
    UIImageView *lingImg1 = [[UIImageView alloc]init];
    [thisTheSuperView addSubview:lingImg1];
    
    
    [lingImg1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(thisTheSuperView.mas_left);
        make.width.equalTo(thisTheSuperView.mas_width);
        make.height.equalTo(@(1));
        make.top.equalTo(thisTheSuperView.mas_top);
    }];
    
    
    UIImageView *lingImg2 = [[UIImageView alloc]init];
    [thisTheSuperView addSubview:lingImg2];
    
    
    UIView *baseView = [[UIView alloc]init];
    
    [thisTheSuperView addSubview:baseView];
    
    
    [lingImg2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(thisTheSuperView.mas_left);
        make.width.equalTo(thisTheSuperView.mas_width);
        make.height.equalTo(@(1));
        make.top.equalTo(baseView.mas_bottom);
    }];
    lingImg2.backgroundColor = [UIColor colorWithHex:0xe6e6e6];
    lingImg1.backgroundColor = [UIColor colorWithHex:0xe6e6e6];
    
    //    CGRect rect = baseView.frame;
    baseView.backgroundColor = [UIColor colorWithHex:0xffffff];
    //    baseView.backgroundColor = [UIColor clearColor];
    
    UIView *viewForColor = [[UIView alloc]init];
    //    viewForColor.backgroundColor = [UIColor colorWithHex:0xffffff];
    [baseView addSubview: viewForColor];
    
    UIImageView *titleLefIV = [[UIImageView alloc]init];
    [baseView addSubview:titleLefIV];
    
    UILabel *titleLabel = [[UILabel alloc]init];
    [baseView addSubview:titleLabel];
    
    MyButtonMainPage *myBtn = [[MyButtonMainPage alloc]init];
    myBtn.Btntag = 0;
    [baseView addSubview:myBtn];
    
    MyButtonMainPage *myBtn1 = [[MyButtonMainPage alloc]init];
    myBtn1.Btntag = 1;
    [baseView addSubview:myBtn1];
    
    MyButtonMainPage *myBtn2 = [[MyButtonMainPage alloc]init];
    myBtn2.Btntag = 2;
    [baseView addSubview:myBtn2];
    
    MyButtonMainPage *myBtn3 = [[MyButtonMainPage alloc]init];
    myBtn3.Btntag = 3;
    [baseView addSubview:myBtn3];
    
    UILabel *titleTipLabel = [[UILabel alloc]init];
    
    [thisTheSuperView addSubview:titleTipLabel];
    
    
    UIImageView *titleTipLabelLeftImg = [[UIImageView alloc]init];
    
    [thisTheSuperView addSubview:titleTipLabelLeftImg];
    
    UIImageView *titleTipLabelRightImg = [[UIImageView alloc]init];
    
    [thisTheSuperView addSubview:titleTipLabelRightImg];
    
    [titleLefIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(baseView.mas_left).offset(18/2);
        make.width.equalTo(@(4/2));
        make.height.equalTo(@(30));
        make.top.equalTo(baseView.mas_top).offset(20/2);
    }];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLefIV.mas_right).offset(18/2);
        //            make.width.equalTo(@(70));
        make.height.equalTo(titleLefIV.mas_height);
        make.centerY.equalTo(titleLefIV.mas_centerY);
    }];
    
    [myBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(baseView.mas_left).offset(50/2);
        make.width.equalTo(myBtn1.mas_width);
        make.height.equalTo(@((124+36)/2));
        make.top.equalTo(titleLabel.mas_bottom).offset(50/3);
        //             make.bottom.equalTo(baseView.mas_bottom).offset(-20);
        
    }];
    [myBtn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(myBtn.mas_right);
        make.width.equalTo(myBtn.mas_width);
        make.height.equalTo(myBtn.mas_height);
        make.bottom.equalTo(myBtn.mas_bottom);
    }];
    [myBtn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(myBtn1.mas_right);
        make.width.equalTo(myBtn1.mas_width);
        make.height.equalTo(myBtn1.mas_height);
        make.bottom.equalTo(myBtn1.mas_bottom);
        //            make.right.equalTo(myBtn3.mas_right).offset(-20);
    }];
    
    [myBtn3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(myBtn2.mas_right);
        make.width.equalTo(myBtn2.mas_width);
        make.height.equalTo(myBtn2.mas_height);
        make.bottom.equalTo(myBtn2.mas_bottom);
        make.right.equalTo(baseView.mas_right).offset(-20);
    }];
    
    [titleTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(thisTheSuperView.mas_centerX);
        make.height.equalTo(@(56/2));
        make.bottom.equalTo(thisTheSuperView.mas_bottom);
    }];
    
    [titleTipLabelLeftImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(titleTipLabel.mas_centerY);
        make.height.equalTo(@(1));
        make.left.equalTo(thisTheSuperView.mas_left).offset(60/2);
        make.right.equalTo(titleTipLabel.mas_left).offset(-40/2);
    }];
    
    [titleTipLabelRightImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(titleTipLabel.mas_centerY);
        make.height.equalTo(@(1));
        make.left.equalTo(titleTipLabel.mas_right).offset(40/2);
        make.right.equalTo(thisTheSuperView.mas_right).offset(-60/2);
    }];
    titleTipLabelRightImg.hidden = YES;
    titleTipLabelLeftImg.hidden = YES;
    [viewForColor mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(baseView.mas_left);
        make.right.equalTo(baseView.mas_right);
        make.top.equalTo(baseView.mas_top);
        make.bottom.equalTo(titleTipLabel.mas_top);
    }];
    [baseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(thisTheSuperView.mas_left);
        make.right.equalTo(thisTheSuperView.mas_right);
        make.top.equalTo(thisTheSuperView.mas_top).offset(1);
        make.bottom.equalTo(titleTipLabel.mas_top).offset(-1);
        make.height.equalTo(@(320/2));
        
    }];
    
    titleLefIV.backgroundColor = [UIColor colorWithHex:0x5da6ff];
    titleLabel.text = @"快捷工具";
    
    titleLabel.textColor = [UIColor colorWithHex:0x4c4c4c];
    titleLabel.font = [UIFont systemFontOfSize:32/2];
    [myBtn setTitle:@"扫码考勤" forState:UIControlStateNormal];
    [myBtn1 setTitle:@"个人任务" forState:UIControlStateNormal];
    [myBtn2 setTitle:@"消息提醒" forState:UIControlStateNormal];
    [myBtn3 setTitle:@"系统设置" forState:UIControlStateNormal];
    
    myBtn.titleLabel.font = [UIFont systemFontOfSize:28/2];
    myBtn1.titleLabel.font = [UIFont systemFontOfSize:28/2];
    myBtn2.titleLabel.font = [UIFont systemFontOfSize:28/2];
    myBtn3.titleLabel.font = [UIFont systemFontOfSize:28/2];
    [myBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [myBtn1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [myBtn2 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [myBtn3 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [myBtn setImage:[UIImage imageNamed:@"移动客户化_12"] forState:UIControlStateNormal];
    [myBtn1 setImage:[UIImage imageNamed:@"移动客户化_14"] forState:UIControlStateNormal];
    [myBtn2 setImage:[UIImage imageNamed:@"移动客户化_16"] forState:UIControlStateNormal];
    [myBtn3 setImage:[UIImage imageNamed:@"移动客户化_18"] forState:UIControlStateNormal];
    
    
    [myBtn setTitleColor:[UIColor colorWithHex:0x808080] forState:UIControlStateNormal];
    [myBtn1 setTitleColor:[UIColor colorWithHex:0x808080] forState:UIControlStateNormal];
    [myBtn2 setTitleColor:[UIColor colorWithHex:0x808080] forState:UIControlStateNormal];
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSInteger badge = [[ud objectForKey:@"badge"] integerValue];
    if (!_borderView) {
        _borderView = [[UIView alloc] init];
    }
    
    
    //    badge +=1;
    //    [ud setObject:[NSString stringWithFormat:@"%zd",badge] forKey:@"badge"];
    NSLog(@"%zd",badge);
    if (badge>0) {
        if (!_badgeLabel) {
            
            
            [baseView addSubview:_borderView];
            [_borderView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(myBtn2.mas_top).offset(0);
                make.left.equalTo(myBtn2.mas_centerX).offset(12);
                make.height.equalTo(@(17));
                make.width.equalTo(@(27));
            }];
            _borderView.layer.masksToBounds = YES;
            _borderView.layer.cornerRadius = 7.4f;
            _borderView.backgroundColor = [UIColor whiteColor];
            _badgeLabel = [[UILabel alloc] init];
            [_borderView addSubview:_badgeLabel];
            [_badgeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(_borderView.mas_centerX);
                make.centerY.equalTo(_borderView.mas_centerY);
                make.height.equalTo(@(15));
                make.width.equalTo(@(25));
            }];
            _badgeLabel.backgroundColor = [UIColor redColor];
            _badgeLabel.layer.masksToBounds = YES;
            _badgeLabel.layer.cornerRadius = 7.0f;
            _badgeLabel.textColor = [UIColor whiteColor];
            //            _badgeLabel.layer.borderWidth = 1.0f;
            //            _badgeLabel.layer.borderColor = [UIColor whiteColor].CGColor;
            _badgeLabel.text = [NSString stringWithFormat:@"%zd",badge];
            _badgeLabel.font = [UIFont systemFontOfSize:8];
            _badgeLabel.textAlignment = NSTextAlignmentCenter;
        }
        
        _badgeLabel.hidden = NO;
        _borderView.hidden = NO;
    }else {
        _borderView.hidden = YES;
        _badgeLabel.hidden = YES;
    }
    
    
    [myBtn3 setTitleColor:[UIColor colorWithHex:0x808080] forState:UIControlStateNormal];
    titleTipLabel.text = @"功能菜单";
    titleTipLabel.hidden = YES;
    titleTipLabel.textAlignment = NSTextAlignmentCenter;
    titleTipLabel.textColor = [UIColor colorWithRed:187/255.0 green:188/255.0 blue:189/255.0 alpha:1];
    
    titleTipLabelLeftImg.backgroundColor = [UIColor colorWithHex:0xdddddd];
    titleTipLabelRightImg.backgroundColor = [UIColor colorWithHex:0xdddddd];
    
    return thisTheSuperView;
}

-(void)btnClick:(MyButtonMainPage *)myBtn{
    NSLog(@"%ld", myBtn.Btntag);
    if(myBtn.Btntag == 1){
        PersonalMissionViewController *pmvc = [[PersonalMissionViewController alloc] init];
        pmvc.tabbarView = self.cusTabView;
        [self.navigationController pushViewController:pmvc animated:YES];
    }else if(myBtn.Btntag ==2){
        MessageAlertViewController *mavc = [[MessageAlertViewController alloc] init];
        mavc.tabbarView = self.cusTabView;
        [self.navigationController pushViewController:mavc animated:YES];
    }
    else if(myBtn.Btntag == 3){
        
        SetUPViewController *sv =[[SetUPViewController alloc]init];
        sv.tabbarView = self.cusTabView;
        [self.navigationController pushViewController:sv animated:YES];
    }
#pragma -mark 扫一扫点击事件
    else if (myBtn.Btntag == 0) {
        ZCZBarViewController *zvc = [[ZCZBarViewController alloc] initWithBlock:^(NSString * data, BOOL succeed) {
            if(succeed){
                NSString *urlStr = [[NSString alloc]initWithString:data];
                NSLog(@"%@", urlStr);
                
                //                NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
                //                [param setObject:str forKey:@"stuId"];
                
                [NetRequest requestUrl:urlStr andParamas:nil andReturnBlock:^(NSData *data, NSError *error) {
                    if(!error&&data!=nil){
                        NSString *str = [[NSString alloc]initWithData:data  encoding:NSUTF8StringEncoding];
                        NSString *useStr = [NSString stringWithFormat:@"%@%@",[str componentsSeparatedByString:@",fieldCnName:" ][0],@"}"];
                        NSData *canUseDate = [useStr dataUsingEncoding:NSUTF8StringEncoding];
                        NSLog(@"%@",useStr);
                        NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:canUseDate options:NSJSONReadingMutableContainers error:nil];
                        NSLog(@"%@", obj);
                        if ([str isEqualToString:@"1"]) {
                            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"考勤" message:@"考勤成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                            alert.delegate = self;
                            [alert show];
                        }else{
                            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"考勤" message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                            alert.delegate = self;
                            [alert show];
                        }
                        NSLog(@"sucess!");
                        _sucess = YES;
                    }else{
                        NSLog(@"%@",error);
                        _sucess = NO;
                    }
                    
                }];
                //            NSLog(@"%@",erro);
                
            }
            
        }];
        
        [self.navigationController presentViewController:zvc animated:YES completion:^{
            
        }];;
    }
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
    {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    if ([[userDefault valueForKey:@"autoLogin"]isEqualToString:@"autoLoginF"]) {
        [self showLabelWithText:@"自动登录失败"];
    }
    
}



- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
    
    //    [_scroView layoutIfNeeded];
    //    _superView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 528+size.height);
    //    _scroView.contentSize = CGSizeMake(self.view.bounds.size.width, 528+size.height);
    
    NSLog(@"%f", self.view.bounds.size.width);
    //    [_superView mas_updateConstraints:^(MASConstraintMaker *make) {
    //        make.width.equalTo(@(self.view.bounds.size.width));
    //    }];
    self.collectionView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    [self.collectionView reloadData];
    [self.view layoutIfNeeded];
    switch (interfaceOrientation) {
        case UIInterfaceOrientationPortrait:
            NSLog(@"%f", self.view.bounds.size.width);
            //home健在下
            break;
        case UIInterfaceOrientationPortraitUpsideDown:
            NSLog(@"%f", self.view.bounds.size.width);
            //home健在上
            break;
        case UIInterfaceOrientationLandscapeLeft:
            NSLog(@"%f", self.view.bounds.size.width);
            
            //home健在左
            break;
        case UIInterfaceOrientationLandscapeRight:
            NSLog(@"%f", self.view.bounds.size.width);
            
            //home健在右
            
            //***
            break;
        default:
            break;
            
    }
    
    
}



- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    _isheng=NO;
}
//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{return NO;}
//- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{}
//这些都可以知道当前的屏幕状态的

@end
